import { defineStore } from "pinia";
import { getAllRoleList, getOrganizationList } from "@/api/manage/manage";
import type { RoleListItem, OrganizationList } from "@/api/manage/model/manage";
import type { TableData } from "views/manage/organization/types";

interface ManageState {
  roleList: RoleListItem[];
  organizationTree: TableData;
}

export const useManageStore = defineStore("manageStore", {
  state: (): ManageState => ({
    roleList: [],
    organizationTree: [],
  }),
  actions: {
    getAllRoleList() {
      return getAllRoleList().then((res: RoleListItem[]) => {
        this.roleList = res;
      });
    },
    getOrganizationList() {
      return getOrganizationList().then((res) => {
        this.organizationTree = (function refactor(
          td: OrganizationList[]
        ): TableData {
          return td.map((item: OrganizationList) => ({
            id: Number(item.id),
            name: item.attributes.name,
            ...(item.children && item.children.length > 0
              ? { children: refactor(item.children) }
              : {}),
          }));
        })(res.children);
      });
    },
  },
  getters: {},
});
